<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-row">
        <view class="search-box">
          <image src="/static/search.png" class="search-icon" />
          <input 
            class="search-input" 
            v-model="searchKeyword" 
            placeholder="搜索联系人..."
            @input="filterContacts"
          />
          <text class="clear-btn" v-if="searchKeyword" @click="clearSearch">×</text>
        </view>
        <view class="header-right">
          <text class="add-text" @click="showAddContact">添加</text>
        </view>
      </view>
    </view>

    <!-- 联系人列表 -->
    <view class="contacts-container">
      <!-- 字母索引 -->
      <view class="letter-index" v-if="!searchKeyword">
        <text 
          class="letter-item" 
          v-for="letter in alphabet" 
          :key="letter"
          @click="scrollToLetter(letter)"
        >
          {{ letter }}
        </text>
      </view>

      <!-- 联系人分组 -->
      <view class="contact-groups">
        <view 
          class="contact-group" 
          v-for="group in filteredContactGroups" 
          :key="group.letter"
        >
          <view class="group-header" :id="'letter-' + group.letter">
            <text class="group-letter">{{ group.letter }}</text>
            <text class="group-count">({{ group.contacts.length }})</text>
          </view>
          <view class="contact-list">
            <view 
              class="contact-item" 
              v-for="contact in group.contacts" 
              :key="contact.id"
              @click="showContactDetail(contact)"
            >
              <view class="contact-avatar">
                <image 
                  :src="contact.avatar || '/static/avatar.png'" 
                  class="avatar-img"
                />
                <view class="online-status" v-if="contact.isOnline"></view>
              </view>
              <view class="contact-info">
                <view class="contact-name-row">
                  <text class="contact-name">{{ contact.name }}</text>
                  <view class="contact-tags" v-if="contact.tags && contact.tags.length">
                    <text 
                      class="contact-tag" 
                      v-for="tag in contact.tags" 
                      :key="tag"
                    >
                      {{ tag }}
                    </text>
                  </view>
                </view>
                <text class="contact-phone">{{ contact.phone }}</text>
                <text class="contact-department" v-if="contact.department">
                  {{ contact.department }}
                </text>
              </view>
              <view class="contact-actions">
                <view class="action-btn call-btn" @click.stop="makeCall(contact)">
                  <image src="/static/phone.png" class="action-btn-icon" />
                </view>
                <view class="action-btn message-btn" @click.stop="sendMessage(contact)">
                  <image src="/static/message.png" class="action-btn-icon" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加联系人弹窗 -->
    <view class="modal" v-if="showAddModal" @click="closeAddContact">
      <view class="modal-content add-contact-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">添加联系人</text>
          <view class="close-btn" @click="closeAddContact">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="add-contact-form">
          <view class="form-item">
            <text class="form-label">姓名</text>
            <input 
              class="form-input" 
              v-model="newContact.name" 
              placeholder="请输入姓名"
            />
          </view>
          <view class="form-item">
            <text class="form-label">手机号</text>
            <input 
              class="form-input" 
              v-model="newContact.phone" 
              placeholder="请输入手机号"
              type="number"
            />
          </view>
          <view class="form-item">
            <text class="form-label">部门</text>
            <picker 
              class="form-picker" 
              :range="departments" 
              @change="onDepartmentChange"
            >
              <text class="picker-text">{{ newContact.department || '请选择部门' }}</text>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">标签</text>
            <view class="tag-selector">
              <view 
                class="tag-option" 
                :class="{ active: newContact.tags.includes(tag) }"
                v-for="tag in availableTags" 
                :key="tag"
                @click="toggleTag(tag)"
              >
                <text class="tag-option-text">{{ tag }}</text>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="form-textarea" 
              v-model="newContact.note" 
              placeholder="请输入备注信息"
            />
          </view>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeAddContact">取消</button>
          <button class="save-btn" @click="saveContact">保存</button>
        </view>
      </view>
    </view>

    <!-- 联系人详情弹窗 -->
    <view class="modal" v-if="showDetailModal" @click="closeContactDetail">
      <view class="modal-content detail-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">联系人详情</text>
          <view class="close-btn" @click="closeContactDetail">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="contact-detail" v-if="selectedContact">
          <view class="detail-avatar">
            <image 
              :src="selectedContact.avatar || '/static/avatar.png'" 
              class="detail-avatar-img"
            />
            <view class="online-status" v-if="selectedContact.isOnline"></view>
          </view>
          <text class="detail-name">{{ selectedContact.name }}</text>
          <text class="detail-phone">{{ selectedContact.phone }}</text>
          <text class="detail-department" v-if="selectedContact.department">
            {{ selectedContact.department }}
          </text>
          <view class="detail-tags" v-if="selectedContact.tags && selectedContact.tags.length">
            <text 
              class="detail-tag" 
              v-for="tag in selectedContact.tags" 
              :key="tag"
            >
              {{ tag }}
            </text>
          </view>
          <text class="detail-note" v-if="selectedContact.note">
            {{ selectedContact.note }}
          </text>
        </view>
        <view class="detail-actions">
          <view class="detail-action-btn" @click="makeCall(selectedContact)">
            <image src="/static/contact.png" class="detail-action-icon" />
            <text class="detail-action-text">拨打电话</text>
          </view>
          <view class="detail-action-btn" @click="sendMessage(selectedContact)">
            <image src="/static/weixin.png" class="detail-action-icon" />
            <text class="detail-action-text">发送消息</text>
          </view>
          <view class="detail-action-btn" @click="editContact(selectedContact)">
            <image src="/static/tools.png" class="detail-action-icon" />
            <text class="detail-action-text">编辑</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 紧急联系人弹窗 -->
    <view class="modal" v-if="showEmergencyModal" @click="closeEmergencyContacts">
      <view class="modal-content emergency-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">紧急联系人</text>
          <view class="close-btn" @click="closeEmergencyContacts">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="emergency-list">
          <view 
            class="emergency-item" 
            v-for="contact in emergencyContacts" 
            :key="contact.id"
            @click="makeCall(contact)"
          >
            <view class="emergency-avatar">
              <image :src="contact.avatar || '/static/avatar.png'" class="emergency-avatar-img" />
            </view>
            <view class="emergency-info">
              <text class="emergency-name">{{ contact.name }}</text>
              <text class="emergency-phone">{{ contact.phone }}</text>
              <text class="emergency-role">{{ contact.role }}</text>
            </view>
            <view class="emergency-call">
              <image src="/static/contact.png" class="emergency-call-icon" />
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const searchKeyword = ref('')
const showAddModal = ref(false)
const showDetailModal = ref(false)
const showEmergencyModal = ref(false)
const selectedContact = ref(null)

// 新联系人数据
const newContact = ref({
  name: '',
  phone: '',
  department: '',
  tags: [],
  note: ''
})

// 字母表
const alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

// 部门列表
const departments = [
  '物业管理部',
  '维修部',
  '安保部',
  '清洁部',
  '绿化部',
  '客服部',
  '行政部',
  '财务部'
]

// 可用标签
const availableTags = [
  '紧急联系人',
  '主管',
  '技术员',
  '值班员',
  '维修工',
  '保安',
  '清洁工'
]

// 联系人数据
const contacts = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    department: '物业管理部',
    avatar: '/static/avatar.png',
    tags: ['主管', '紧急联系人'],
    note: '物业部主管，负责日常管理工作',
    isOnline: true
  },
  {
    id: 2,
    name: '李四',
    phone: '13800138002',
    department: '维修部',
    avatar: '/static/avatar.png',
    tags: ['技术员'],
    note: '电气维修技术员',
    isOnline: false
  },
  {
    id: 3,
    name: '王五',
    phone: '13800138003',
    department: '安保部',
    avatar: '/static/avatar.png',
    tags: ['保安', '值班员'],
    note: '夜班保安队长',
    isOnline: true
  },
  {
    id: 4,
    name: '赵六',
    phone: '13800138004',
    department: '清洁部',
    avatar: '/static/avatar.png',
    tags: ['清洁工'],
    note: '负责教学楼清洁工作',
    isOnline: false
  },
  {
    id: 5,
    name: '钱七',
    phone: '13800138005',
    department: '维修部',
    avatar: '/static/avatar.png',
    tags: ['维修工'],
    note: '水管维修工',
    isOnline: true
  }
])

// 紧急联系人
const emergencyContacts = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    role: '物业部主管',
    avatar: '/static/avatar.png'
  },
  {
    id: 6,
    name: '孙八',
    phone: '13800138006',
    role: '安保部主管',
    avatar: '/static/avatar.png'
  },
  {
    id: 7,
    name: '周九',
    phone: '13800138007',
    role: '维修部主管',
    avatar: '/static/avatar.png'
  }
])

// 计算属性
const filteredContacts = computed(() => {
  if (!searchKeyword.value) return contacts.value
  return contacts.value.filter(contact => 
    contact.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    contact.phone.includes(searchKeyword.value) ||
    contact.department.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const filteredContactGroups = computed(() => {
  const groups = {}
  
  filteredContacts.value.forEach(contact => {
    const firstLetter = contact.name.charAt(0).toUpperCase()
    if (!groups[firstLetter]) {
      groups[firstLetter] = []
    }
    groups[firstLetter].push(contact)
  })
  
  return Object.keys(groups)
    .sort()
    .map(letter => ({
      letter,
      contacts: groups[letter].sort((a, b) => a.name.localeCompare(b.name))
    }))
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const filterContacts = () => {
  // 搜索功能已通过计算属性实现
}

const clearSearch = () => {
  searchKeyword.value = ''
}

const showAddContact = () => {
  showAddModal.value = true
  resetNewContact()
}

const closeAddContact = () => {
  showAddModal.value = false
  resetNewContact()
}

const resetNewContact = () => {
  newContact.value = {
    name: '',
    phone: '',
    department: '',
    tags: [],
    note: ''
  }
}

const onDepartmentChange = (e) => {
  newContact.value.department = departments[e.detail.value]
}

const toggleTag = (tag) => {
  const index = newContact.value.tags.indexOf(tag)
  if (index > -1) {
    newContact.value.tags.splice(index, 1)
  } else {
    newContact.value.tags.push(tag)
  }
}

const saveContact = () => {
  if (!newContact.value.name.trim() || !newContact.value.phone.trim()) {
    uni.showToast({ title: '请填写姓名和手机号', icon: 'none' })
    return
  }
  
  const contact = {
    id: Date.now(),
    ...newContact.value,
    avatar: '/static/avatar.png',
    isOnline: false
  }
  
  contacts.value.push(contact)
  contacts.value.sort((a, b) => a.name.localeCompare(b.name))
  
  uni.showToast({ title: '添加成功', icon: 'success' })
  closeAddContact()
}

const showContactDetail = (contact) => {
  selectedContact.value = contact
  showDetailModal.value = true
}

const closeContactDetail = () => {
  showDetailModal.value = false
  selectedContact.value = null
}

const makeCall = (contact) => {
  uni.makePhoneCall({
    phoneNumber: contact.phone,
    success: () => {
      console.log('拨打电话成功')
    },
    fail: () => {
      uni.showToast({ title: '拨打电话失败', icon: 'none' })
    }
  })
}

const sendMessage = (contact) => {
  uni.showToast({ title: '消息功能开发中', icon: 'none' })
}

const editContact = (contact) => {
  uni.showToast({ title: '编辑功能开发中', icon: 'none' })
}

const closeEmergencyContacts = () => {
  showEmergencyModal.value = false
}

const scrollToLetter = (letter) => {
  const element = document.getElementById('letter-' + letter)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

// 生命周期
onMounted(() => {
  // 页面初始化
})
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

.add-text {
  font-size: 28rpx;
  color: #3D76FF;
}

/* 搜索栏 */
.search-section {
  background: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
}
.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 32rpx;
  padding: 0 20rpx;
  height: 64rpx;
}
.header-right {
  margin-left: 10rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 28rpx;
  color: #333;
}

.clear-btn {
  font-size: 32rpx;
  color: #999;
  margin-left: 12rpx;
}

/* 联系人容器 */
.contacts-container {
  position: relative;
}

/* 字母索引 */
.letter-index {
  position: fixed;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.1);
  border-radius: 20rpx;
  padding: 10rpx 5rpx;
  z-index: 50;
}

.letter-item {
  display: block;
  font-size: 20rpx;
  color: #333;
  padding: 4rpx 8rpx;
  text-align: center;
}

/* 联系人分组 */
.contact-groups {
  background: #fff;
}

.group-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #eee;
}

.group-letter {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.group-count {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.contact-list {
  background: #fff;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.contact-avatar {
  position: relative;
  margin-right: 20rpx;
}

.avatar-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.online-status {
  position: absolute;
  bottom: 5rpx;
  right: 5rpx;
  width: 20rpx;
  height: 20rpx;
  background: #4CAF50;
  border-radius: 50%;
  border: 2rpx solid #fff;
}

.contact-info {
  flex: 1;
  min-width: 0;
}

.contact-name-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.contact-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;
}

.contact-tags {
  display: flex;
  flex-wrap: wrap;
}

.contact-tag {
  font-size: 20rpx;
  color: #3D76FF;
  background: #f0f7ff;
  padding: 4rpx 8rpx;
  border-radius: 12rpx;
  margin-right: 8rpx;
}

.contact-phone {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 4rpx;
  display: block;
}

.contact-department {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.contact-actions {
  display: flex;
  gap: 15rpx;
}

.action-btn {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.call-btn {
  background: #4CAF50;
}

.message-btn {
  background: #2196F3;
}

.action-btn-icon {
  width: 45rpx;
  height: 45rpx;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 90%;
  max-height: 80%;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-icon {
  font-size: 40rpx;
  color: #999;
}

/* 添加联系人弹窗 */
.add-contact-modal {
  height: 1200rpx;
  max-width: 600rpx;
}

.add-contact-form {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background: #fff;
}

.form-picker {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.tag-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.tag-option {
  padding: 10rpx 20rpx;
  border: 2rpx solid #eee;
  border-radius: 20rpx;
  background: #fff;
}

.tag-option.active {
  border-color: #3D76FF;
  background: #f0f7ff;
}

.tag-option-text {
  font-size: 24rpx;
  color: #333;
}

.tag-option.active .tag-option-text {
  color: #3D76FF;
}

.form-textarea {
  width: 100%;
  height: 120rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #fff;
  resize: none;
}

.modal-footer {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  gap: 20rpx;
  margin-bottom: 50rpx;
}

.cancel-btn, .save-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.save-btn {
  background: #3D76FF;
  color: #fff;
}

/* 联系人详情弹窗 */
.detail-modal {
  width: 90%;
  max-width: 500rpx;
}

.contact-detail {
  padding: 40rpx 30rpx;
  text-align: center;
}

.detail-avatar {
  position: relative;
  display: inline-block;
  margin-bottom: 20rpx;
}

.detail-avatar-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
}

.detail-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.detail-phone {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.detail-department {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 15rpx;
  display: block;
}

.detail-tags {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 15rpx;
}

.detail-tag {
  font-size: 22rpx;
  color: #3D76FF;
  background: #f0f7ff;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.detail-note {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  display: block;
}

.detail-actions {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  gap: 20rpx;
}

.detail-action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 10rpx;
}

.detail-action-icon {
  width: 40rpx;
  height: 40rpx;
  margin-bottom: 10rpx;
}

.detail-action-text {
  font-size: 24rpx;
  color: #333;
}

/* 紧急联系人弹窗 */
.emergency-modal {
  width: 90%;
  max-width: 500rpx;
}

.emergency-list {
  padding: 20rpx 30rpx;
}

.emergency-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.emergency-item:last-child {
  border-bottom: none;
}

.emergency-avatar {
  margin-right: 20rpx;
}

.emergency-avatar-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.emergency-info {
  flex: 1;
}

.emergency-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.emergency-phone {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 4rpx;
  display: block;
}

.emergency-role {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.emergency-call {
  width: 60rpx;
  height: 60rpx;
  background: #ff6b6b;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.emergency-call-icon {
  width: 30rpx;
  height: 30rpx;
}
</style>